package com.lzp.wechat.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzp.wechat.common.constants.RedisConstants;
import com.lzp.wechat.common.utils.RedisCacheUtils;
import com.lzp.wechat.entity.WeiXinParameter;
import com.lzp.wechat.service.WeiXinUserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class WeiXinUserInfoServiceImpl implements WeiXinUserInfoService {

    @Autowired
    private WeiXinParameter weiXinParameter;

    @Autowired
    private RedisCacheUtils redisCacheUtils;

    @Override
    public String getUserInfoByOpenId(String openid) {
        String access_token = redisCacheUtils.get(RedisConstants.ACCESS_TOKEN).toString();
        String url = weiXinParameter.getGetUserInfoByOpenIdUrl();
        url = url.replace("ACCESS_TOKEN", access_token).replace("OPENID", openid);
        String result = HttpUtil.get(url);
        log.info("调用腾讯获取用户信息响应：{}", result);
        return result;
    }

    @Override
    public String getUserInfoByCode(String code) {
        // 1.根据code获取授权的access_token和openid
        String url = weiXinParameter.getAuthorizeAccessTokenUrl();
        url = url.replace("APPID", weiXinParameter.getAppId())
                .replace("SECRET", weiXinParameter.getAppSecret())
                .replace("CODE", code);
        log.info("根据code获取授权的access_token和openid Url:{}", url);
        String result = HttpUtil.get(url);
        log.info("根据code获取授权的access_token和openid响应：{}", result);
        JSONObject jsonObject = JSON.parseObject(result);
        // 2.根据openid获取用户信息
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        String getUserInfoByOpenIdUrl = weiXinParameter.getGetUserInfoByOpenIdUrl();
        getUserInfoByOpenIdUrl= getUserInfoByOpenIdUrl.replace("ACCESS_TOKEN", access_token).replace("OPENID", openid);
        log.info("根据openid获取用户信息 Url:{}", getUserInfoByOpenIdUrl);
        result = HttpUtil.get(getUserInfoByOpenIdUrl);
        log.info("根据openid获取用户信息响应：{}", result);
        return result;
    }

}
